import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/device_controller.dart';
import '../widgets/device_grid_item.dart';
import '../widgets/device_list_item.dart';
import '../../../translations/app_translations.dart';
import '../../../utils/themes/app_theme_extension.dart';
import '../../../models/device_model.dart';

class DeviceView extends GetView<DeviceController> {
  const DeviceView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();
    
    return Scaffold(
      appBar: AppBar(
        title: Text(LocaleKeys.deviceManagement.tr),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              showSearch(
                context: context,
                delegate: DeviceSearchDelegate(
                  controller,
                  showDeviceActions: (ctx, id) => _showDeviceActions(ctx, id),
                ),
              );
            },
          ),
          IconButton(
            onPressed: () {
              _showFilterDialog(context);
            },
            icon: const Icon(Icons.filter_list),
          ),
        ],
      ),
      body: RefreshIndicator(
        onRefresh: () => controller.refreshDevices(),
        child: Stack(
          children: [
            Obx(() {
              if (controller.isLoading.value) {
                return const SizedBox(
                  height: 80,
                  child: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              }
              
              if (controller.devices.isEmpty) {
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.devices,
                        size: 80,
                        color: extension?.disabledText ?? Colors.grey,
                      ),
                      const SizedBox(height: 16),
                      Text(
                        LocaleKeys.noDevices.tr,
                        style: theme.textTheme.titleMedium?.copyWith(
                          color: extension?.disabledText ?? Colors.grey,
                        ),
                      ),
                    ],
                  ),
                );
              }
              
              return GridView.builder(
                controller: controller.scrollController,
                padding: const EdgeInsets.all(12),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 0.85,
                  crossAxisSpacing: 8,
                  mainAxisSpacing: 8,
                ),
                itemCount: controller.devices.length + 1, // 加1用于显示加载更多指示器
                itemBuilder: (context, index) {
                  if (index == controller.devices.length) {
                    if (controller.isLoadingMore.value) {
                      return const SizedBox(
                        height: 60,
                        child: Center(
                          child: CircularProgressIndicator(),
                        ),
                      );
                    }
                    return const SizedBox.shrink();
                  }
                  
                  final device = controller.devices[index];
                  return DeviceGridItem(
                    device: device,
                    onDetailsTap: () {
                      controller.viewDeviceDetail(device.deviceId);
                                        },
                    onDataTap: () {
                      controller.viewDeviceData(device.deviceId);
                                        },
                    onDataTableTap: () {
                      controller.viewDeviceDataTable(device.deviceId);
                                        },
                    onActionTap: () {
                      _showDeviceActions(context, device.deviceId);
                                        },
                  );
                },
              );
            }),
            
            // 顶部加载条
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Obx(() => controller.isRefreshing.value 
                ? const SizedBox(
                    height: 2,
                    child: LinearProgressIndicator(),
                  )
                : const SizedBox.shrink()
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => controller.addNewDevice(),
        tooltip: LocaleKeys.addDevice.tr,
        child: const Icon(Icons.add),
      ),
    );
  }
  
  void _showFilterDialog(BuildContext context) {
    final theme = Theme.of(context);
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(LocaleKeys.filterDevice.tr),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              LocaleKeys.deviceStatus.tr,
              style: theme.textTheme.titleSmall,
            ),
            const SizedBox(height: 8),
            DropdownButton<int?>(
              isExpanded: true,
              hint: Text(LocaleKeys.deviceStatus.tr),
              value: controller.filterStatus.value,
              items: [
                DropdownMenuItem<int?>(
                  value: null,
                  child: Text(LocaleKeys.allStatus.tr),
                ),
                DropdownMenuItem<int?>(
                  value: 0,
                  child: Text(LocaleKeys.deviceInactive.tr),
                ),
                DropdownMenuItem<int?>(
                  value: 1,
                  child: Text(LocaleKeys.deviceOnline.tr),
                ),
                DropdownMenuItem<int?>(
                  value: 2,
                  child: Text(LocaleKeys.deviceOffline.tr),
                ),
                DropdownMenuItem<int?>(
                  value: 3,
                  child: Text(LocaleKeys.deviceDisabled.tr),
                ),
              ],
              onChanged: (value) {
                controller.filterStatus.value = value;
              },
            ),
            const SizedBox(height: 16),
            Text(
              LocaleKeys.productFilter.tr,
              style: theme.textTheme.titleSmall,
            ),
            const SizedBox(height: 8),
            TextField(
              controller: controller.productKeyController,
              decoration: InputDecoration(
                labelText: LocaleKeys.productKey.tr,
                hintText: LocaleKeys.enterProductKey.tr,
                border: const OutlineInputBorder(),
                contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              controller.resetFilters();
              Get.back();
            },
            child: Text(LocaleKeys.reset.tr),
          ),
          ElevatedButton(
            onPressed: () {
              controller.applyFilters();
              Get.back();
            },
            child: Text(LocaleKeys.apply.tr),
          ),
        ],
      ),
    );
  }
  
  void _showDeviceActions(BuildContext context, int? deviceId) {
    if (deviceId == null) return;
    
    // 查找设备，判断是否有国标ID
    Device? device;
    if (controller.devices.isNotEmpty) {
      device = controller.devices.firstWhereOrNull((d) => d.deviceId == deviceId);
    }
    if (device == null && controller.searchResults.isNotEmpty) {
      device = controller.searchResults.firstWhereOrNull((d) => d.deviceId == deviceId);
    }
    
    final bool hasVideo = device != null && device.wvpDeviceId.isNotEmpty;
    
    showModalBottomSheet(
      context: context,
      builder: (context) => Wrap(
        children: [
          ListTile(
            leading: const Icon(Icons.info_outline),
            title: Text(LocaleKeys.viewDetails.tr),
            onTap: () {
              Get.back();
              controller.viewDeviceDetail(deviceId);
            },
          ),
          ListTile(
            leading: const Icon(Icons.data_usage),
            title: Text(LocaleKeys.deviceData.tr),
            onTap: () {
              Get.back();
              controller.viewDeviceData(deviceId);
            },
          ),
          // 仅当设备有国标ID时显示视频选项
          if (hasVideo) 
            ListTile(
              leading: const Icon(Icons.videocam, color: Colors.red),
              title: Text('查看视频监控'),
              onTap: () {
                Get.back();
                controller.viewDeviceVideo(deviceId);
            },
          ),
          ListTile(
            leading: const Icon(Icons.edit),
            title: Text(LocaleKeys.editDevice.tr),
            onTap: () {
              Get.back();
              controller.editDevice(deviceId);
            },
          ),
          ListTile(
            leading: const Icon(Icons.delete_outline),
            title: Text(LocaleKeys.deleteDevice.tr),
            onTap: () {
              Get.back();
              _showDeleteConfirmDialog(context, deviceId);
            },
          ),
        ],
      ),
    );
  }
  
  void _showDeleteConfirmDialog(BuildContext context, int deviceId) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(LocaleKeys.deleteConfirm.tr),
        content: Text(LocaleKeys.deleteConfirmMessage.tr),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: Text(LocaleKeys.cancel.tr),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
            ),
            onPressed: () {
              Get.back();
              controller.deleteDevice(deviceId);
            },
            child: Text(LocaleKeys.deleteDevice.tr),
          ),
        ],
      ),
    );
  }
}

class DeviceSearchDelegate extends SearchDelegate<String> {
  final DeviceController controller;
  final TextStyle titleStyle = const TextStyle(fontWeight: FontWeight.bold);
  final Function(BuildContext, int?) showDeviceActions;
  
  DeviceSearchDelegate(this.controller, {required this.showDeviceActions});
  
  @override
  String get searchFieldLabel => LocaleKeys.searchDeviceHint.tr;
  
  IconData _getDeviceStatusIcon(int? status) {
    switch (status) {
      case 0: return Icons.device_unknown;
      case 1: return Icons.check_circle_outline;
      case 2: return Icons.offline_bolt;
      case 3: return Icons.block;
      default: return Icons.device_unknown;
    }
  }
  
  Color _getDeviceStatusColor(int? status) {
    switch (status) {
      case 0: return Colors.grey;
      case 1: return Colors.green;
      case 2: return Colors.orange;
      case 3: return Colors.red;
      default: return Colors.grey;
    }
  }
  
  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        onPressed: () {
          query = '';
        },
        icon: const Icon(Icons.clear),
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      onPressed: () {
        close(context, '');
      },
      icon: const Icon(Icons.arrow_back),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    controller.searchDevices(query);
    return _buildSearchResults(context);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    if (query.isEmpty) {
      return Center(
        child: Text(LocaleKeys.searchDeviceHint.tr),
      );
    }
    
    controller.searchDevices(query);
    return _buildSearchResults(context);
  }
  
  Widget _buildSearchResults(BuildContext context) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();
    
    return Obx(() {
      if (controller.isSearching.value) {
        return const Center(child: CircularProgressIndicator());
      }
      
      if (controller.searchResults.isEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.search_off,
                size: 64,
                color: extension?.disabledText ?? Colors.grey,
              ),
              const SizedBox(height: 16),
              Text(
                LocaleKeys.noMatchingDevices.tr,
                style: theme.textTheme.bodyLarge?.copyWith(
                  color: extension?.disabledText ?? Colors.grey,
                ),
              ),
            ],
          ),
        );
      }
      
      return ListView.builder(
        itemCount: controller.searchResults.length,
        itemBuilder: (context, index) {
          final device = controller.searchResults[index];
          return DeviceListItem(
            device: device,
            onDetailsTap: () {
              close(context, '');
              controller.viewDeviceDetail(device.deviceId);
                        },
            onDataTap: () {
              close(context, '');
              controller.viewDeviceData(device.deviceId);
                        },
            onDataTableTap: () {
              close(context, '');
              controller.viewDeviceDataTable(device.deviceId);
                        },
            onActionTap: () {
              showDeviceActions(context, device.deviceId);
            },
          );
        },
      );
    });
  }
} 